package com.adgox.tiantianbiting.home.programDetail;

import android.app.ActivityManager;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Messenger;
import android.support.v4.app.Fragment;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.adgox.tiantianbiting.R;
import com.adgox.tiantianbiting.adapter.CommentAdapter;
import com.adgox.tiantianbiting.adapter.CustomerServiceBean;
import com.adgox.tiantianbiting.adapter.ProgramChooseAdapter;
import com.adgox.tiantianbiting.bean.BaseResponseBean;
import com.adgox.tiantianbiting.bean.CommentBean;
import com.adgox.tiantianbiting.bean.PageBean;
import com.adgox.tiantianbiting.bean.ProgramChooseBean;
import com.adgox.tiantianbiting.bean.ProgramCostBean;
import com.adgox.tiantianbiting.bean.ShareUrlBean;
import com.adgox.tiantianbiting.bean.SubProgramBean;
import com.adgox.tiantianbiting.bean.UserInfo;
import com.adgox.tiantianbiting.home.programCustomBuy.ProgramCustomBuyActivity;
import com.adgox.tiantianbiting.mine.wallet.MyWalletActivity;
import com.adgox.tiantianbiting.music.MusicService;
import com.adgox.tiantianbiting.net.callback.JsonCallback;
import com.adgox.tiantianbiting.utils.ApiConstant;
import com.adgox.tiantianbiting.utils.DialogUtils;
import com.adgox.tiantianbiting.utils.TimeUtils;
import com.adgox.tiantianbiting.widget.MyExpandableListView;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.rae.swift.session.SessionManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ProgramDetailActivity extends AppCompatActivity implements ProgramDetailContract.View, ProgramChooseAdapter.onItemClickListener, View.OnClickListener, SeekBar.OnSeekBarChangeListener, CommentAdapter.onGroupItemClickListener, TextView.OnEditorActionListener {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.img_book)
    ImageView imgBook;
    @BindView(R.id.seekBar)
    SeekBar seekBar;
    @BindView(R.id.tv_curr_time)
    TextView tvCurrTime;
    @BindView(R.id.tv_total_time)
    TextView tvTotalTime;
    @BindView(R.id.tv_book_name)
    TextView tvBookName;
    @BindView(R.id.tv_listen_num)
    TextView tvListenNum;
    @BindView(R.id.indicator_intro)
    View indicatorIntro;
    @BindView(R.id.indicator_choose)
    View indicatorChoose;
    @BindView(R.id.tv_intro)
    WebView tvIntro;
    @BindView(R.id.rv_choose)
    RecyclerView rvChoose;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.tv_buy_all)
    TextView tvBuyAll;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.btn_intro)
    TextView btnIntro;
    @BindView(R.id.btn_choose)
    TextView btnChoose;
    @BindView(R.id.tv_try_listen)
    TextView tvTryListen;
    @BindView(R.id.icon_next)
    ImageView iconNext;
    @BindView(R.id.icon_play)
    ImageView iconPlay;
    //    @BindView(R.id.player_progress)
//    LinearLayout playerProgress;

    @BindView(R.id.tv_season_num)
    TextView tvSeasonNum;
    @BindView(R.id.iv_collect)
    ImageView ivCollect;
    @BindView(R.id.tv_collect)
    TextView tvCollect;
    @BindView(R.id.btn_comment)
    TextView btnComment;
    @BindView(R.id.indicator_comment)
    View indicatorComment;
    @BindView(R.id.rv_comment)
    MyExpandableListView rvComment;
    @BindView(R.id.fl_comment)
    FrameLayout flComment;
    @BindView(R.id.et_comment)
    EditText etComment;
    @BindView(R.id.tv_empty)
    TextView tvEmpty;
    @BindView(R.id.fl_comment_show)
    FrameLayout flCommentShow;
    private ProgramDetailContract.Presenter mPresenter;
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private int programId;
    private String programName;
    private int seasonId;
    private int currentPage = 1;//选集当前页数
    private int maxPage = 20;
    private int currentCommentPage = 1;//评论当前页数
    private ProgramChooseAdapter adapter;
    private int totalPages;//选集总页数
    private int totalCommentPages;//评论总页数
    private List<ProgramChooseBean> mList = new ArrayList<>();

    //定义节目类型，分集列表adapter里要用到
    private int programType;
    public static int TYPE_FREE = 1;
    public static int TYPE_BUY_ALL = 2;
    public static int TYPE_BUY_EVERY = 3;


    private TextView tvBuyThis;
    private TextView tvNext10;
    private TextView tvCustom;
    private int selectedColor;
    private int unSelectedColor;
    private ImageView ivAuto;
    private TextView tvCost;
    private TextView tvToBuy;
    private int clickPosition = -1;
    private Dialog dialog;
    private SubProgramBean programInfo;
    private int NOTIFACATION_ID = 123;
    private NotificationManager nm;
    private Notification notification;
    private RemoteViews contentViews;
    private String CHANNEL_ID = "ttbt_channel";
    private String CHANNEL_NAME = "ttbt_name";
    private int duration;
    private int progress;
    private MyReceiver receiver;
    private Intent intentService;
    private int serviceProgramId;
    private boolean isCollected;
    private Dialog dDialog;
    private double next10Cost;
    private int buyNum = 1;
    private int clockSecond;
    private int currentTime;//播放进度时间
    private int currentPosition;//seekbar的进度值
    private ArrayList<ArrayList<CommentBean>> childList = new ArrayList<>();
    private ArrayList<CommentBean> groupList = new ArrayList<>();
    private CommentAdapter commentAdapter;
    private int groupClickPosition;
    private int CHOOSE_PAGE = 1;
    private int COMMENT_PAGE = 2;
    private int visiablePage = 1;
    private int discussId; //回复的评论id，为0的话就是回复节目，不为0则是回复具体评论
    private String TAG;
    private Dialog consumerDialog;
    private int userId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_program_detail);
        ButterKnife.bind(this);
        new ProgramDetailPresenterImpl(this);

        //判断后台service是否正在运行
        ifServiceAlive();

        programId = getIntent().getIntExtra("programId", -1);
        programName = getIntent().getStringExtra("programName");

        if (programId == -1 || "".equals(programName)) {
            Toast.makeText(this, "获取节目内容出错", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        //判断是否有随机红包
        if (SessionManager.getDefault().isLogin()){
            userId = ((UserInfo) SessionManager.getDefault().getUser()).getId();
            DialogUtils.checkRandomRed(userId,this,"详情页");
        }

//        playerProgress.setVisibility(View.GONE);
        tvTitle.setText(programName);
        DialogUtils.showLoadingDialog(this);
        //获取节目详情
        mPresenter.getProgramInfo(programId);
        //seekbar拖动监听
        seekBar.setOnSeekBarChangeListener(this);
        //注册广播接收器
        registerReceiver();
        //初始化通知栏
//        initNotification();
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    private void ifServiceAlive() {
        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> runningServices = am.getRunningServices(Integer.MAX_VALUE);
        for (ActivityManager.RunningServiceInfo info : runningServices) {
            if (info.service.getClassName().equals("com.adgox.tiantianbiting.music.MusicService")) {
                intentService = new Intent(ProgramDetailActivity.this, MusicService.class);
                intentService.putExtra("option", "reattach");
                startService(intentService);
            }
        }
    }

    private void registerReceiver() {
        receiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.adgox.tiantianbiting.music.MusicService");
        this.registerReceiver(receiver, intentFilter);
    }


    @Override
    public void setPresenter(ProgramDetailContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @OnClick(R.id.btn_intro)
    public void onIntroClicked() {
        indicatorChoose.setVisibility(View.INVISIBLE);
        indicatorComment.setVisibility(View.INVISIBLE);
        indicatorIntro.setVisibility(View.VISIBLE);
        tvIntro.setVisibility(View.VISIBLE);
        flCommentShow.setVisibility(View.GONE);
        rvChoose.setVisibility(View.GONE);
        flComment.setVisibility(View.GONE);
    }

    @OnClick(R.id.btn_choose)
    public void onChooseClicked() {
        indicatorIntro.setVisibility(View.INVISIBLE);
        indicatorComment.setVisibility(View.INVISIBLE);
        indicatorChoose.setVisibility(View.VISIBLE);
        tvIntro.setVisibility(View.GONE);
        flCommentShow.setVisibility(View.GONE);
        rvChoose.setVisibility(View.VISIBLE);
        visiablePage = CHOOSE_PAGE;
        flComment.setVisibility(View.GONE);
    }

    @OnClick(R.id.btn_comment)
    public void onViewClicked() {
        indicatorComment.setVisibility(View.VISIBLE);
        indicatorChoose.setVisibility(View.INVISIBLE);
        indicatorIntro.setVisibility(View.INVISIBLE);
        tvIntro.setVisibility(View.GONE);
        rvChoose.setVisibility(View.GONE);
        flCommentShow.setVisibility(View.VISIBLE);
        visiablePage = COMMENT_PAGE;
        flComment.setVisibility(View.VISIBLE);
    }

    @Override
    public void onSetProgramInfo(SubProgramBean bean) {
        if (bean == null) {
            DialogUtils.dismiss();
            Toast.makeText(this, "获取数据失败", Toast.LENGTH_SHORT).show();
            return;
        }
        programInfo = bean;
        seasonId = bean.getSeasonId();
        //节目信息展示
        tvTitle.setText(programInfo.getTitle());
        Glide.with(this).load(programInfo.getImageUrl()).centerCrop().into(imgBook);
        tvBookName.setText(programInfo.getTitle());
        tvListenNum.setText(programInfo.getListenNum() + "");
        tvSeasonNum.setText(programInfo.getTotalSeason() + "集");
//        tvIntro.setText(Html.fromHtml(programInfo.getDescribe()));
        tvIntro.loadDataWithBaseURL(null, getHtmlData(programInfo.getDescribe()), "text/html", "utf-8", null);

        //记录收藏状态
        isCollected = programInfo.getMarkStatus() == 0 ? true : false;
        ivCollect.setImageResource(isCollected ? R.drawable.icon_collected : R.drawable.icon_uncollected);
        tvCollect.setTextColor(isCollected ? Color.parseColor("#e64340") : Color.parseColor("#353535"));
        tvCollect.setText(isCollected ? "已收藏" : "收藏");

        tvBuyAll.setText("全集" + programInfo.getTotalCount() + "听币");
        /**
         * 判断是否是免费节目，是的话则不显示底部栏，
         * 如果不是，则再判断，是否支持分集购买，
         * 如果支持，则还是不显示底部栏，
         * 如果不支持，则显示底部栏
         */
        llBottom.setVisibility(programInfo.getCategory() == 0 ?
                View.GONE : (programInfo.getEverySeasonBuy() == 0) ? View.VISIBLE : View.GONE);
        /**
         * 节目类型判断，同上
         */
        programType = programInfo.getCategory() == 0 ? TYPE_FREE : (programInfo.getEverySeasonBuy() == 0 ? TYPE_BUY_ALL : TYPE_BUY_EVERY);

        //获取节目选集第一页
        mPresenter.getProgramChooseInfo(programId, currentPage, maxPage);
        mPresenter.getComment(programId, currentPage, maxPage);
        etComment.setOnEditorActionListener(this);
    }

    private String getHtmlData(String describe) {
        String head = "<head>" +
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " +
                "<style>img{max-width: 100%; width:auto; height:auto!important;}</style>" +
                "</head>";
        return "<html>" + head + "<body>" + describe + "</body></html>";
    }

    @Override
    public void onGetProgramInfoFailed(String msg) {
        DialogUtils.dismiss();
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSetProgramChooseInfo(PageBean<ProgramChooseBean> list) {
        if ((list == null || list.getData() == null) || list.getData().size() == 0) {
            Toast.makeText(this, "获取数据失败", Toast.LENGTH_SHORT).show();
            return;
        }
        totalPages = list.getTotalPages();

        mList.addAll(list.getData());

        if (adapter == null) {
            LinearLayoutManager manager = new LinearLayoutManager(this);
            manager.setSmoothScrollbarEnabled(true);
            manager.setAutoMeasureEnabled(true);

            rvChoose.setLayoutManager(manager);
            rvChoose.setNestedScrollingEnabled(false);
            rvChoose.setHasFixedSize(true);
            adapter = new ProgramChooseAdapter(list.getData(), programType);
            adapter.setOnItemClickListener(this);
            adapter.setClickPostion(clickPosition);
            rvChoose.setAdapter(adapter);
        } else {
            adapter.addDatas(list.getData());
            adapter.notifyDataSetChanged();
        }

        scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY == (v.getChildAt(0).getMeasuredHeight()) - v.getMeasuredHeight()) {
                    //加载更多
                    if (visiablePage == 1) {
                        if (currentPage < totalPages) {
                            currentPage++;
                            showLoading();
                            mPresenter.getProgramChooseInfo(programId, currentPage, maxPage);
                        } else {
                            Toast.makeText(ProgramDetailActivity.this, "没有更多了", Toast.LENGTH_SHORT).show();
                        }
                    } else if (visiablePage == 2) {
                        if (currentCommentPage < totalCommentPages) {
                            currentCommentPage++;
                            showLoading();
                            mPresenter.getComment(programId, currentCommentPage, maxPage);
                        } else {
                            Toast.makeText(ProgramDetailActivity.this, "没有更多了", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }
        });

        //找到历史播放集数，标黄
        adapter.setClickPostion(programInfo.getCurrentSeason() - 1);
        adapter.notifyDataSetChanged();
    }

    private void showLoading() {
        DialogUtils.showLoadingDialog(this);
    }

    @Override
    public void onGetProgramChooseInfoFailed(String msg) {

    }

    @Override
    public void onSetNext10Cost(ProgramCostBean bean) {
        next10Cost = bean.getTotalPrice();
        tvNext10.setText("后10章" + bean.getTotalPrice() + "听币");
    }

    @Override
    public void onGetNext10CostFailed(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onAddCollectSuccess() {
        tvCollect.setTextColor(Color.parseColor("#e64340"));
        tvCollect.setText("已收藏");
        ivCollect.setImageResource(R.drawable.icon_collected);
        isCollected = true;
    }

    @Override
    public void onAddCollectFailed(String msg) {
        Toast.makeText(ProgramDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCancelCollectSuccess() {
        tvCollect.setTextColor(Color.parseColor("#353535"));
        tvCollect.setText("收藏");
        ivCollect.setImageResource(R.drawable.icon_uncollected);
        isCollected = false;
    }

    @Override
    public void onCancelCollectFailed(String msg) {
        Toast.makeText(ProgramDetailActivity.this, msg, Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onBuyAllSuccess() {
        //购买成功，刷新节目选集列表
        if (dDialog != null) dDialog.dismiss();
        mList.clear();
        adapter.clear();
        currentPage = 1;
        mPresenter.getProgramChooseInfo(programId, currentPage, maxPage);
    }

    @Override
    public void onBuyAllFailed(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onBuyEverySuccess() {
        if (dDialog != null) dDialog.dismiss();
        mList.clear();
        adapter.clear();
        currentPage = 1;
        mPresenter.getProgramChooseInfo(programId, currentPage, maxPage);
    }

    @Override
    public void onBuyEveryFailed(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSetComment(PageBean<CommentBean> datas) {
        if (datas == null || datas.getData() == null || datas.getData().size() == 0) {
            //没有评论
            tvEmpty.setVisibility(View.VISIBLE);
            rvComment.setVisibility(View.INVISIBLE);
            return;
        }
        tvEmpty.setVisibility(View.GONE);
        rvComment.setVisibility(View.VISIBLE);
        ArrayList<ArrayList<CommentBean>> newChildList = new ArrayList<>();
        for (int i = 0; i < datas.getData().size(); i++) {
            newChildList.add(null);
        }
        groupList.addAll(datas.getData());
        childList.addAll(newChildList);

        if (commentAdapter == null) {
            commentAdapter = new CommentAdapter((ArrayList<CommentBean>) datas.getData(),newChildList);
            commentAdapter.setOnGroupItemClickListener(this);
        } else {
            commentAdapter.addDatas((ArrayList<CommentBean>) datas.getData(), newChildList);
        }
        rvComment.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                discussId = groupList.get(groupPosition).getId();
                etComment.setHint("回复 " + groupList.get(groupPosition).getUser().getWxNickname() + ":");
                return true;
            }
        });
        rvComment.setAdapter(commentAdapter);
    }

    @Override
    public void onGetCommentFailed(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSetSubComment(List<CommentBean> datas) {
        commentAdapter.addSubComment((ArrayList<CommentBean>) datas,groupClickPosition);
        rvComment.expandGroup(groupClickPosition);

    }

    @Override
    public void onGetSubCommentFailed(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSendCommentSuccess() {
        tvEmpty.setVisibility(View.GONE);
        rvComment.setVisibility(View.VISIBLE);
        Toast.makeText(this, "添加评论成功", Toast.LENGTH_SHORT).show();
        etComment.getText().clear();
        etComment.setHint("说点什么");
        currentCommentPage = 1;
        groupList.clear();
        childList.clear();
        if (commentAdapter!=null)commentAdapter.clear();
        mPresenter.getComment(programId, currentCommentPage, maxPage);
    }

    @Override
    public void onSendCommentFailed(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @OnClick(R.id.img_finish)
    public void onFinishClicked() {
        finish();
    }

    @Override
    public void onItemClick(View view, int position) {
        clickPosition = position;
        ProgramChooseBean bean = mList.get(position);
        seasonId = bean.getId();
        //支持分集购买节目
        if (programType == TYPE_BUY_EVERY) {
            //不可试听集
            if (bean.getTryStatus() != 0) {
                //未购买，弹购买窗
                if (bean.getBuySelf() == 0) {
                    popBuyDialog();
                } else {
                    //已购买，直接播放
                    play(bean.getPlayUrl());
                }
            } else {
                //可试听集，直接播放
                play(bean.getPlayUrl());
            }
        } else

            //仅支持全集购买节目
            if (programType == TYPE_BUY_ALL) {
                //不可试听集
                if (bean.getTryStatus() == 1) {
                    //未购买，toast提示购买
                    if (bean.getBuySelf() == 0) {
                        Toast.makeText(this, "本节目仅支持全集购买", Toast.LENGTH_SHORT).show();
                    } else {
                        //已购买，直接播放
                        play(bean.getPlayUrl());
                    }
                } else {
                    //可试听 直接播放
                    play(bean.getPlayUrl());
                }
            } else

                //全免费集
                if (programType == TYPE_FREE) {
                    play(bean.getPlayUrl());
                }
    }


    //底部弹出分集购买dialog
    public void popBuyDialog() {
        selectedColor = getResources().getColor(R.color.dialogSelected);
        unSelectedColor = getResources().getColor(R.color.dialogUnSelected);

        dialog = new Dialog(this, R.style.BottomDialog);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_buy_by_every, null);

        TextView tvDialogTitle = view.findViewById(R.id.tv_dialog_title);
        tvBuyThis = view.findViewById(R.id.tv_buy_this);
        tvNext10 = view.findViewById(R.id.tv_next10);
        tvCustom = view.findViewById(R.id.tv_custom);
        ivAuto = view.findViewById(R.id.iv_auto);
        tvCost = view.findViewById(R.id.tv_cost);
        tvToBuy = view.findViewById(R.id.tv_tobuy);

        tvDialogTitle.setText("从第" + (clickPosition + 1) + "集开始购买");
        tvBuyThis.setText("本章" + mList.get(clickPosition).getPrice() + "听币");
        tvBuyThis.setOnClickListener(this);
        tvNext10.setOnClickListener(this);
        tvCustom.setOnClickListener(this);
        tvCost.setText(mList.get(clickPosition).getPrice() + "听币");
        tvToBuy.setOnClickListener(this);

        dialog.setContentView(view);
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setDimAmount(0f);
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
        showLoading();
        mPresenter.getNext10Cost(programId, mList.get(clickPosition).getId());
    }

    private void choose(TextView tv) {
        tvBuyThis.setTextColor(unSelectedColor);
        tvNext10.setTextColor(unSelectedColor);
        tvCustom.setTextColor(unSelectedColor);
        tvBuyThis.setBackgroundResource(R.drawable.bg_textview_buy_dialog_unselected);
        tvNext10.setBackgroundResource(R.drawable.bg_textview_buy_dialog_unselected);
        tvCurrTime.setBackgroundResource(R.drawable.bg_textview_buy_dialog_unselected);

        tv.setTextColor(selectedColor);
        tv.setBackgroundResource(R.drawable.bg_textview_buy_dialog_selected);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_buy_this:
                choose(tvBuyThis);
                buyNum = 1;
                tvCost.setText(mList.get(clickPosition).getPrice() + "听币");
                break;
            case R.id.tv_next10:
                choose(tvNext10);
                buyNum = 10;
                tvCost.setText(next10Cost + "听币");
                break;
            case R.id.tv_custom:
                Intent intent = new Intent(ProgramDetailActivity.this, ProgramCustomBuyActivity.class);
                intent.putExtra("programId", programId);
                startActivity(intent);
                dialog.dismiss();
                break;
            case R.id.tv_tobuy:
                dialog.dismiss();
                popBuyDetailDialog(buyNum, buyNum == 1 ? mList.get(clickPosition).getPrice() : next10Cost, TYPE_BUY_EVERY);
                break;
            case R.id.img_X:
                dDialog.dismiss();
                break;
            case R.id.tv_to_recharge:
                startActivity(new Intent(this, MyWalletActivity.class));
                dDialog.dismiss();
                break;
        }
    }

    @OnClick(R.id.icon_play)
    public void onPlayClicked() {
        if (mList == null || mList.size() == 0) return;
        if (serviceProgramId > 0 && serviceProgramId != programId) {
            //当前后台播放的节目和本页不是同一节目，先杀死
            intentService = new Intent(ProgramDetailActivity.this, MusicService.class);
            intentService.putExtra("option", "kill");
            startService(intentService);
            seekBar.setProgress(0);
            tvCurrTime.setText("00:00");
            tvTotalTime.setText("00:00");
            serviceProgramId = programId;
        }

//        if (playerProgress.getVisibility() != View.VISIBLE) {
//            playerProgress.setVisibility(View.VISIBLE);
//        }
        clickPosition = programInfo.getCurrentSeason() - 1;
//        play(programInfo.getPlayUrl());
        intentService = new Intent(ProgramDetailActivity.this, MusicService.class);
        intentService.putExtra("option", "play");
        intentService.putExtra("messenger", new Messenger(new Handler()));
        intentService.putExtra("path", programInfo.getPlayUrl());
        intentService.putExtra("programId", programId);
        intentService.putExtra("seasonId", seasonId);
        intentService.putExtra("clickPosition", clickPosition);
        intentService.putExtra("img", programInfo.getShareImageUrl());
        intentService.putExtra("name", programInfo.getTitle());
        startService(intentService);
        adapter.setClickPostion(clickPosition);
        adapter.notifyDataSetChanged();
    }

    private void play(String path) {

        intentService = new Intent(ProgramDetailActivity.this, MusicService.class);
        intentService.putExtra("option", "choose");
        intentService.putExtra("programId", programId);
        intentService.putExtra("seasonId", seasonId);
        intentService.putExtra("clickPosition", clickPosition);
        intentService.putExtra("path", path);
        intentService.putExtra("img", programInfo.getShareImageUrl());
        intentService.putExtra("name", programInfo.getTitle());
        startService(intentService);
        seekBar.setProgress(0);
        tvCurrTime.setText("00:00");
        tvTotalTime.setText("00:00");
        serviceProgramId = programId;

        //播放成功后，让选集标题变色
        adapter.setClickPostion(clickPosition);
        adapter.notifyDataSetChanged();
    }


    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
        //b是判断进度改变是否是来自用户的操作
        if (!b) return;
        intentService = new Intent(ProgramDetailActivity.this, MusicService.class);
        intentService.putExtra("option", "seekPlay");
        intentService.putExtra("messenger", new Messenger(new Handler()));
        intentService.putExtra("progress", i);
        startService(intentService);
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        //不管
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        //也不管
    }

    @OnClick(R.id.icon_next)
    public void onNextClicked() {
        if (clickPosition >= mList.size() - 1) {
            Toast.makeText(this, "已经到最后一集啦!", Toast.LENGTH_SHORT).show();
            return;
        }
        ProgramChooseBean programChooseBean = mList.get(clickPosition + 1);
        if (programType == TYPE_FREE) {
            clickPosition = clickPosition + 1;
            seasonId = programChooseBean.getId();
            play(programChooseBean.getPlayUrl());
        } else if (programType == TYPE_BUY_ALL) {
            if (programChooseBean.getTryStatus() == 1 && programChooseBean.getBuySelf() == 0) {
                Toast.makeText(this, "本节目仅支持全集购买", Toast.LENGTH_SHORT).show();
            } else {
                clickPosition = clickPosition + 1;
                seasonId = programChooseBean.getId();
                play(programChooseBean.getPlayUrl());
            }
        } else if (programType == TYPE_BUY_EVERY) {
            if (programChooseBean.getTryStatus() == 1 && programChooseBean.getBuySelf() == 0) {
                popBuyDialog();
            } else {
                clickPosition = clickPosition + 1;
                seasonId = programChooseBean.getId();
                play(programChooseBean.getPlayUrl());
            }
        }
    }

    @OnClick(R.id.ll_collect)
    public void onStarClicked() {
        Gson gson = new Gson();
        HashMap<String, Object> map = new HashMap<>();
        map.put("programId", programId);
        map.put("status", 2);
        map.put("seasonId", 1);
        map.put("userId", ((UserInfo) SessionManager.getDefault().getUser()).getId());

        String s = gson.toJson(map);
        DialogUtils.showLoadingDialog(this);
        if (isCollected) {
            //取消收藏
            mPresenter.cancelCollect(s);
        } else {
            //收藏
            mPresenter.addCollect(s);
        }

    }

    @OnClick(R.id.tv_try_listen)
    public void onTryListenClicked() {
        //仅支持全集购买的节目的试听
        iconPlay.performClick();
    }

    @OnClick(R.id.tv_buy_all)
    public void onBuyAllClicked() {
        popBuyDetailDialog(programInfo.getTotalSeason(), programInfo.getTotalCount(), TYPE_BUY_ALL);
    }

    private void popBuyDetailDialog(int seasonNum, final double cost, final int type) {
        dDialog = new Dialog(this);
        Window window = dDialog.getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        window.setContentView(R.layout.dialog_buy_detail);
        window.setBackgroundDrawableResource(android.R.color.transparent);
        ImageView imgX = dDialog.findViewById(R.id.img_X);
        ImageView imgBook = dDialog.findViewById(R.id.img_book);
        TextView tvBookName = dDialog.findViewById(R.id.tv_book_name);
        TextView tvBuySeasons = dDialog.findViewById(R.id.tv_buy_seasons);
        TextView tvTotalCost = dDialog.findViewById(R.id.tv_total_cost);
        TextView tvToRecharge = dDialog.findViewById(R.id.tv_to_recharge);
        TextView tvBuy = dDialog.findViewById(R.id.tv_buy);

        Glide.with(this).load(programInfo.getShareImageUrl()).into(imgBook);
        tvBookName.setText(programInfo.getTitle());
        tvBuySeasons.setText("集数 " + seasonNum + "集");
        tvTotalCost.setText("价格 " + cost + "听币");
        UserInfo user = SessionManager.getDefault().getUser();
        if (user.getBalance() < cost) {
            tvToRecharge.setVisibility(View.VISIBLE);
        } else {
            tvToRecharge.setVisibility(View.GONE);
        }

        imgX.setOnClickListener(this);
        tvToRecharge.setOnClickListener(this);
        tvBuy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (type == TYPE_BUY_ALL) {
                    mPresenter.buyAll(cost, programId);
                } else if (type == TYPE_BUY_EVERY) {
                    if (buyNum == 1) {
                        ArrayList<Long> longs = new ArrayList<>();
                        longs.add((long) mList.get(clickPosition).getId());
                        mPresenter.buyEvery(programId, longs);
                    } else if (buyNum == 10) {
                        ArrayList<Long> longs = new ArrayList<>();
                        int position = clickPosition;
                        for (int i = 0; i < 10; i++) {
                            if (position <= mList.size() - 1) {
                                longs.add((long) mList.get(position).getId());
                                position++;
                            }
                        }
                        mPresenter.buyEvery(programId, longs);
                    }

                }
            }
        });
        dDialog.setCanceledOnTouchOutside(false);
        dDialog.show();
    }

//    @OnClick(R.id.icon_last)
//    public void onLastClicked() {
//        if (clickPosition <= 0) {
//            Toast.makeText(this, "已经是第一集啦", Toast.LENGTH_SHORT).show();
//            return;
//        }
//        ProgramChooseBean programChooseBean = mList.get(clickPosition - 1);
//        if (programType == TYPE_FREE) {
//            clickPosition = clickPosition - 1;
//            seasonId = programChooseBean.getId();
//            play(programChooseBean.getPlayUrl());
//        } else if (programType == TYPE_BUY_ALL) {
//            if (programChooseBean.getTryStatus() == 1 && programChooseBean.getBuySelf() == 0) {
//                Toast.makeText(this, "本节目仅支持全集购买", Toast.LENGTH_SHORT).show();
//            } else {
//                clickPosition = clickPosition - 1;
//                seasonId = programChooseBean.getId();
//                play(programChooseBean.getPlayUrl());
//            }
//        } else if (programType == TYPE_BUY_EVERY) {
//            if (programChooseBean.getTryStatus() == 1 && programChooseBean.getBuySelf() == 0) {
//                popBuyDialog();
//            } else {
//                clickPosition = clickPosition - 1;
//                seasonId = programChooseBean.getId();
//                play(programChooseBean.getPlayUrl());
//            }
//        }
//    }

    @OnClick(R.id.ll_list)
    public void onScrollClicked() {
        btnChoose.performClick();

        int[] rvLocation = new int[2];
        rvChoose.getLocationOnScreen(rvLocation);

        int[] imgLocation = new int[2];
        imgBook.getLocationOnScreen(imgLocation);

        scrollView.smoothScrollTo(0, rvLocation[1] - imgLocation[1]);


    }

    @OnClick(R.id.ll_clock)
    public void onClockClicked() {
        final ArrayList<String> clockTimes = new ArrayList<>();
        clockTimes.add("不限时间");
        clockTimes.add("10分钟");
        clockTimes.add("20分钟");
        clockTimes.add("30分钟");
        clockTimes.add("50分钟");
        clockTimes.add("60分钟");
        clockTimes.add("100分钟");

        final ArrayList<Integer> clockSeconds = new ArrayList<>();
        clockSeconds.add(0);
        clockSeconds.add(600);
        clockSeconds.add(1200);
        clockSeconds.add(1800);
        clockSeconds.add(3000);
        clockSeconds.add(3600);
        clockSeconds.add(6000);
        OptionsPickerView pickerView = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                clockSecond = clockSeconds.get(options1);
                if (clockSecond == 0) {
                    //取消倒计时
                    handler.removeCallbacks(runnable);
                } else {
                    handler.postDelayed(runnable, 1000);
                }
            }
        }).build();
        pickerView.setPicker(clockTimes);
        pickerView.show();
    }

    @OnClick(R.id.tv_customer_service)
    public void onCustomerServiceClick() {
        OkGo.<BaseResponseBean<CustomerServiceBean>>get(ApiConstant.BASE_URL+ApiConstant.GET_CUSTOMER_SERVICE_QR)
                .params("type",1)
                .execute(new JsonCallback<BaseResponseBean<CustomerServiceBean>>() {
                    @Override
                    public void onSuccess(Response<BaseResponseBean<CustomerServiceBean>> response) {
                        if ("0".equals(response.body().getCode())){
                            popCustomerServiceDialog(response.body().getData().getLocation());
                        }
                    }
                });
    }

    private void popCustomerServiceDialog(String location) {
        consumerDialog = new Dialog(this, R.style.TransparentDialog);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_customer_service, null);
        consumerDialog.setContentView(view);
        ImageView ivClose = consumerDialog.findViewById(R.id.iv_close_dialog);
        ImageView ivQR = consumerDialog.findViewById(R.id.iv_QR);
        Log.e(TAG, "popCustomerServiceDialog: "+location );
        Glide.with(this).load(location).into(ivQR);
        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                consumerDialog.dismiss();
            }
        });
        Window window = consumerDialog.getWindow();
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.WRAP_CONTENT);
        consumerDialog.show();
    }

    @Override
    public void onGroupItemClick(View view, int position) {
        if (groupList.get(position).getCountDiscuss() <= 0) {
            return;
        }
        if (childList.get(position) != null && childList.get(position).size() > 0) {
            return;
        }
        groupClickPosition = position;
        showLoading();
        mPresenter.getSubComment(groupList.get(position).getId());
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEND) {
            if (etComment.getText().toString().isEmpty()||etComment.getText().toString().trim() == "") {
                Toast.makeText(this, "评论内容不能为空", Toast.LENGTH_SHORT).show();
                return false;
            }

            HashMap<String, Object> map = new HashMap<>();
            map.put("content", etComment.getText().toString().trim());
            map.put("programId", programId);
            map.put("userId", ((UserInfo) SessionManager.getDefault().getUser()).getId());
            if (discussId > 0) {
                map.put("discussId", discussId);
            }
            Gson gson = new Gson();
            String s = gson.toJson(map);
            mPresenter.sendComment(s);
        }
        return false;
    }

    @OnClick(R.id.ll_download)
    public void onDownloadClicked() {
        Toast.makeText(this, "暂未开放，敬请期待", Toast.LENGTH_SHORT).show();
    }

    @OnClick(R.id.ll_share)
    public void onShareClicked() {
        OkGo.<BaseResponseBean<ShareUrlBean>>get(ApiConstant.BASE_URL + ApiConstant.GET_SHARE_URL)
                .params("flg", "go_download")
                .execute(new JsonCallback<BaseResponseBean<ShareUrlBean>>() {
                    @Override
                    public void onSuccess(Response<BaseResponseBean<ShareUrlBean>> response) {
                        if ("0".equals(response.body().getCode()) && response.body().getData() != null) {
                            DialogUtils.showShareDialog(ProgramDetailActivity.this, response.body().getData().getLocation());
                        } else {
                            Toast.makeText(ProgramDetailActivity.this, "获取分享信息失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            String playStatus = bundle.getString("playStatus");
            currentPosition = bundle.getInt("currentPosition");
            if (currentPosition != 0) {
                if (bundle.getInt("serviceProgramId") == programId) {
                    seekBar.setProgress(currentPosition);
                    tvCurrTime.setText(TimeUtils.MSToTime(currentPosition));
                } else {
                    seekBar.setMax(0);
                    seekBar.setProgress(0);
                }
            }
            if ("play".equals(playStatus)) {
                //开始播放
//                playerProgress.setVisibility(View.VISIBLE);
                duration = bundle.getInt("duration");
                if (duration != 0) {
                    seekBar.setMax(duration);
                    tvTotalTime.setText(TimeUtils.MSToTime(duration));
                }
                iconPlay.setImageResource(R.drawable.icon_delay2);

                //记录历史记录
                addHistory();

            } else if ("pause".equals(playStatus)) {
                iconPlay.setImageResource(R.drawable.icon_play2);
            } else if ("continue".equals(playStatus)) {
                iconPlay.setImageResource(R.drawable.icon_delay2);
            } else if ("end".equals(playStatus)) {
                intentService = new Intent(ProgramDetailActivity.this, MusicService.class);
                stopService(intentService);
                iconPlay.setImageResource(R.drawable.icon_play2);
                seekBar.setProgress(0);
                tvCurrTime.setText("00:00");
                tvTotalTime.setText("00:00");
//                playerProgress.setVisibility(View.GONE);
            } else if ("reattach".equals(playStatus)) {
                serviceProgramId = bundle.getInt("programId");
                //如果当前页和播放内容一致的话
                if (serviceProgramId == programId) {
                    seasonId = bundle.getInt("seasonId");
                    clickPosition = bundle.getInt("clickPosition");
                    if (adapter != null) {
                        adapter.setClickPostion(clickPosition);
                        adapter.notifyDataSetChanged();
                    }
                    if (bundle.getBoolean("isPlaying", true)) {
                        iconPlay.setImageResource(R.drawable.icon_delay2);
                    } else {
                        iconPlay.setImageResource(R.drawable.icon_play2);
                    }
                    seekBar.setMax(bundle.getInt("duration"));
                    tvTotalTime.setText(TimeUtils.MSToTime(bundle.getInt("duration")));
//                    playerProgress.setVisibility(View.VISIBLE);
                } else {
                    //打开页和播放页不是同一个节目,不用处理
                }
            }
        }
    }

    //添加收听历史
    private void addHistory() {
        Gson gson = new Gson();
        HashMap<String, Object> map = new HashMap<>();
        map.put("programId", programId);
        map.put("status", 0);
        map.put("seasonId", mList.get(clickPosition).getId());
        map.put("userId", ((UserInfo) SessionManager.getDefault().getUser()).getId());
        String s = gson.toJson(map);
        mPresenter.addHistory(s);
    }

    //定时任务
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            clockSecond--;
            if (clockSecond > 0) {
                handler.postDelayed(runnable, 1000);
            } else {
                intentService = new Intent(ProgramDetailActivity.this, MusicService.class);
                intentService.putExtra("option", "pause");
                startService(intentService);
            }
        }
    };


    //播放进度条更新runnable
    Runnable progressRunnable = new Runnable() {
        @Override
        public void run() {
            currentTime++;
            tvCurrTime.setText(TimeUtils.SecondToTime(currentTime));
            handler.postDelayed(progressRunnable, 1000);
        }
    };
}
